<?php

namespace app\common\model\order;

use app\common\model\Cart;
use app\common\model\Freightconfig;
use app\common\model\goods\Goods;
use app\common\model\goods\Spec;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\User;
use app\common\model\user\Address;
use think\Db;
use think\Model;


class Order extends Model
{





    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'paytime_text',
        'order_status_text',
        'sendtime_text',
        'order_type_text',
        'taketime_text'
    ];



    public function getPayTypeList()
    {
        return ['1' => __('Pay_type 1'), '2' => __('Pay_type 2'), '3' => __('Pay_type 3'), '4' => __('Pay_type 4')];
    }

    public function getOrderStatusList()
    {
        return ['0' => __('Order_status 0'), '10' => __('Order_status 10'), '20' => __('Order_status 20'), '30' => __('Order_status 30'), '40' => __('Order_status 40'), '-1' => __('Order_status -1')];
    }

    public function getOrderTypeList()
    {
        return ['1' => __('Order_type 1'), '2' => __('Order_type 2')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSendtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sendtime']) ? $data['sendtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_type']) ? $data['order_type'] : '');
        $list = $this->getOrderTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setSendtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function goods()
    {
        return $this->hasMany(OrderGoods::class, 'order_id', 'id');
    }
    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    static function yuOrder($cart_ids, $uid, $order_type, $address_id = 0, $type = 1, $order_class = 1)
    {
        $user = User::get($uid);
        $goodsList = collection(Cart::with(['spec', 'goods'])->whereIn('cart.id', $cart_ids)->select())->toArray();
        $freight = $total_fee = $original_price = $total_points = 0;
        foreach ($goodsList as $k => &$v) {
            $product = $v['spec'];
            if ($v['type'] == 2) {
                $total_points += bcmul($product['points'], $v['num'], 2);
            }

            $original_price += bcmul($product['price'], $v['num'], 2);

            if ($order_class == 1) {

                $product['price'] = self::getGoodsPrice($user, $product['price']);
            }

            $total_fee += bcmul($product['price'], $v['num'], 2);
        }
        if ($order_type == 1) {
            $freight = config('site.freight') ?? 0;
            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get([$address_id]);
                $data['addressInfo'] = $addressInfo;
                $data['address_id'] = $address_id;
            } else {
                $addressInfo = Address::getDefaultAddress($uid);
                if ($addressInfo) {
                    $data['addressInfo'] = $addressInfo;
                    $data['address_id'] = $addressInfo['id'];
                }
            }
            if (isset($addressInfo['province']) && $addressInfo['province']) {
                $province = $addressInfo['province'];
                $freightconfig = Freightconfig::whereLike('city', '%' . $province . '%')->find();
                if (isset($freightconfig) && $freightconfig && $freightconfig['freight'] > 0) {
                    $freight = $freightconfig['freight'];
                }
            }
        }
        $data['goodsList'] = $goodsList;
        $data['total_num'] = array_sum(array_column($goodsList, 'num'));
        $data['total_fee'] = round($total_fee, 2);
        $data['pay_fee'] = round($total_fee + $freight, 2);
        $data['freight'] = round($freight, 2);
        $data['total_points'] = $total_points;
        $data['user_id'] = $uid;
        $data['cart_ids'] = $cart_ids;
        $data['original_price'] = $original_price;
        if ($type == 2) {
            Cart::whereIn('id', $cart_ids)->delete();
        }
        return $data;
    }

    static function getGoodsPrice($user, $price)
    {
        //获取折扣价
        $distance = 0;

        if ($user && $user->userlevel) {
            if ($user->userlevel->agent_rate ?? 0) {
                $distance += $price * $user->userlevel->agent_rate / 100;
            }
            if ($user->level_id >= 2) {
                $distance += $price * 0.30;
            }
        }
        return bcsub($price, $distance, 2);
    }

    static function addOrder($param, $is_yue, $order_type = 1, $order_class = 1)
    {
        extract($param);
        Db::startTrans();
        try {
            if ($order_type == 1) {
                if (!isset($address_id) || !$address_id) {
                    exception('收货地址错误');
                }
            }
            if (!isset($total_num) || $total_num <= 0) {
                exception('购买数量错误');
            }
            if ($is_yue) {
                $userInfo = User::get($user_id);
                if ($userInfo->money >= $total_fee) {
                    $pay_money = $total_fee;
                } else {
                    $pay_money = $userInfo->money;
                }
                $pay_fee = bcsub($total_fee, $pay_money, 2);
            }
            $order = [
                'user_id' => $user_id,
                'sn' => sn('order', 'sn', 'NO'),
                'total_num' => $total_num,
                'total_fee' => $original_price,
                'address_id' => isset($address_id) && $address_id ? $address_id : 0,
                'contact' => $addressInfo['contact'] ?? '',
                'telephone' => $addressInfo['telephone'] ?? '',
                'province' => $addressInfo['province'] ?? '',
                'city' => $addressInfo['city'] ?? '',
                'area' => $addressInfo['area'] ?? '',
                'address' => $addressInfo['address'] ?? '',
                'pay_fee' => $pay_fee,
                'freight' => $freight,
                'pay_money' => $pay_money ?? 0,
                'pay_point' => $order_class == 3 ? $total_points : 0,
                'order_class' => $order_class,
                'order_type' => $order_type,
            ];
            $res = Order::create($order);
            foreach ($goodsList as $v) {
                Spec::checkGoods($v);
                $product = Spec::get($v['spec_id']);
                $total_price = bcmul($v['spec']['price'], $v['num'], 2);
                $data = [
                    'order_id' => $res->id,
                    'goods_id' => $v['goods_id'],
                    'spec_id' => $v['spec_id'],
                    'goods_num' => $v['num'],
                    'goods_name' => $v['goods']['title'],
                    'goods_type' => $v['goods']['type'],
                    'goods_price' => $v['spec']['price'],
                    'total_price' => $total_price,
                    'image' => $v['goods']['image'],
                    'pay_fee' => $total_price,
                    'spec_info' => json_encode($product),
                    'first_cate' => $v['goods']['first_cate'],
                    'two_cate' => $v['goods']['two_cate'],
                ];
                OrderGoods::create($data, true);
                Spec::reduceInventory($v['goods_id'], $v['spec_id'], $v['num']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return $res->id;
    }

    static function check_goods($param)
    {

        extract($param);
        $goods = Goods::get($id);
        $user = User::get($uid);
        if ($goods['type'] == 2) {
            if ($user['level_id'] < 1) {
                // exception('请到VIP专区任意下单后,才可购买', 1);
            }
            $ids = Order::where('order_status', '>', '0')->where('order_class',  '2')->where('user_id', $uid)->column('id');
            $count = OrderGoods::whereIn('order_id', $ids)->count();
            if ($count && $user['num'] < $num) {
                // $this->error('限购商品【' . $goods['title'] . '】已购买');
                exception('不满足复购条件：邀请三个好友下单', 1);
            }
        }

        if ($goods['type'] == 4) {
            $minlevel = config('site.minlevel');
            if ($user['level_id'] < $minlevel) {
                exception('超级VIP专区,非超级VIP不可购买', 1);
            }
            $limit = config('site.limit');
            if ($limit > 0) {
                if ($num > $limit) {
                    exception('超级VIP专区,限购' . $limit . '个', 1);
                }
                $count = Order::where('order_status', '>', '0')->where('order_class',  '4')->where('user_id', $uid)->count();
                if ($count > $limit) {
                    exception('超级VIP专区,限购' . $limit . '次', 1);
                }
            }
        }
    }

    static function confirmOrder($data)
    {
        extract($data);
        try {
            $order = Order::get($id);
            if (!$order) {
                exception('订单不存在');
            }
            if (!in_array($order->order_status, ['20', '30'])) {
                exception('订单状态错误');
            }
            $order->taketime = time();
            $order->order_status = '40';
            $order->save();
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
}
